package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheConstant;
import com.hmdp.utils.DataBaseConstant;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    // 线程池
    private static  final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result getById(Long id) {
        // 1. 根据商户id查询redis缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CacheConstant.SHOP_CACHE + id);
        // 2. 判断缓存中是否存在对应商户
        if (StrUtil.isBlank(shopJson)){
            return null;
        }
            if (shopJson == ""){
                return Result.fail("商户不存在");
            }
            else{
                // 存在
                RedisData redisData = BeanUtil.toBean(shopJson, RedisData.class);
                Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
                // 判断缓存是否过期
                LocalDateTime expireTime = redisData.getExpireTime();
                if (expireTime.isAfter(LocalDateTime.now())){
                    // 没过期
                    return Result.ok(shop);
                }
                // 过期
                // 尝试获取锁
                boolean tryLock = tryLock("lock:shop");
                if (tryLock){
                        // 获取到锁
                        // 开启独立线程, 重建缓存, 刷新缓存时间
                        CACHE_REBUILD_EXECUTOR.submit(()->{
                            try {
                                String newShopJson = JSONUtil.toJsonStr(shop);
                                stringRedisTemplate.opsForValue().set(CacheConstant.SHOP_CACHE + id,newShopJson);
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                unLock("lock:shop");
                            }
                        });
                }
                return Result.ok(shop);
            }
    }
    @Override
    @Transactional
    public Result update(Shop shop) {
        // 1. 先更新数据库
        Long id = shop.getId();
        if (id == null){
            return Result.fail("用户id不存在");
        }
        updateById(shop);
        // 2. 后删除缓存
        stringRedisTemplate.delete(CacheConstant.SHOP_CACHE + shop.getId());
        return null;
    }
    // 尝试获取锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1");
        return BooleanUtil.isTrue(flag);
    }
    // 释放锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
}
